import React, { useState } from 'react';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import {
  Box,
  Button,
  Container,
  TextField,
  Typography,
  Link,
  Paper,
  useTheme,
  useMediaQuery,
  Alert,
} from '@mui/material';
import { useNavigate, useSearchParams } from 'react-router-dom';
import authService from '../../services/auth.service';

const validationSchema = Yup.object({
  email: Yup.string()
    .email('请输入有效的邮箱地址')
    .required('邮箱地址不能为空'),
});

const newPasswordValidationSchema = Yup.object({
  password: Yup.string()
    .min(6, '密码长度不能少于6个字符')
    .required('密码不能为空'),
  confirmPassword: Yup.string()
    .oneOf([Yup.ref('password')], '两次输入的密码不一致')
    .required('请确认密码'),
});

interface AuthService {
  resetPassword: (email: string) => Promise<void>;
  updatePassword: (token: string, newPassword: string) => Promise<void>;
}

export const ResetPassword: React.FC = () => {
  const [error, setError] = useState<string>('');
  const [success, setSuccess] = useState<string>('');
  const [searchParams] = useSearchParams();
  const token = searchParams.get('token');
  const navigate = useNavigate();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));

  const resetPasswordFormik = useFormik({
    initialValues: {
      email: '',
    },
    validationSchema,
    onSubmit: async (values) => {
      try {
        await authService.resetPassword(values.email);
        setSuccess('重置密码链接已发送到您的邮箱，请查收');
      } catch (err: any) {
        setError(err.response?.data?.message || '发送重置密码邮件失败，请重试');
      }
    },
  });

  const newPasswordFormik = useFormik({
    initialValues: {
      password: '',
      confirmPassword: '',
    },
    validationSchema: newPasswordValidationSchema,
    onSubmit: async (values) => {
      try {
        await authService.updatePassword(token || '', values.password);
        setSuccess('密码重置成功，请使用新密码登录');
        setTimeout(() => navigate('/login'), 2000);
      } catch (err: any) {
        setError(err.response?.data?.message || '重置密码失败，请重试');
      }
    },
  });

  return (
    <Container component="main" maxWidth="xs">
      <Box
        sx={{
          marginTop: 8,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
        }}
      >
        <Paper
          elevation={3}
          sx={{
            padding: isMobile ? 2 : 4,
            width: '100%',
            borderRadius: 2,
          }}
        >
          <Typography component="h1" variant="h5" align="center" gutterBottom>
            {token ? '设置新密码' : '重置密码'}
          </Typography>
          {error && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {error}
            </Alert>
          )}
          {success && (
            <Alert severity="success" sx={{ mb: 2 }}>
              {success}
            </Alert>
          )}
          {token ? (
            <Box component="form" onSubmit={newPasswordFormik.handleSubmit} sx={{ mt: 1 }}>
              <TextField
                margin="normal"
                required
                fullWidth
                name="password"
                label="新密码"
                type="password"
                id="password"
                value={newPasswordFormik.values.password}
                onChange={newPasswordFormik.handleChange}
                error={newPasswordFormik.touched.password && Boolean(newPasswordFormik.errors.password)}
                helperText={newPasswordFormik.touched.password && newPasswordFormik.errors.password}
              />
              <TextField
                margin="normal"
                required
                fullWidth
                name="confirmPassword"
                label="确认新密码"
                type="password"
                id="confirmPassword"
                value={newPasswordFormik.values.confirmPassword}
                onChange={newPasswordFormik.handleChange}
                error={newPasswordFormik.touched.confirmPassword && Boolean(newPasswordFormik.errors.confirmPassword)}
                helperText={newPasswordFormik.touched.confirmPassword && newPasswordFormik.errors.confirmPassword}
              />
              <Button
                type="submit"
                fullWidth
                variant="contained"
                sx={{ mt: 3, mb: 2 }}
              >
                设置新密码
              </Button>
            </Box>
          ) : (
            <Box component="form" onSubmit={resetPasswordFormik.handleSubmit} sx={{ mt: 1 }}>
              <TextField
                margin="normal"
                required
                fullWidth
                id="email"
                label="邮箱地址"
                name="email"
                autoComplete="email"
                autoFocus
                value={resetPasswordFormik.values.email}
                onChange={resetPasswordFormik.handleChange}
                error={resetPasswordFormik.touched.email && Boolean(resetPasswordFormik.errors.email)}
                helperText={resetPasswordFormik.touched.email && resetPasswordFormik.errors.email}
              />
              <Button
                type="submit"
                fullWidth
                variant="contained"
                sx={{ mt: 3, mb: 2 }}
              >
                发送重置链接
              </Button>
            </Box>
          )}
          <Box sx={{ textAlign: 'center' }}>
            <Link href="/login" variant="body2">
              返回登录
            </Link>
          </Box>
        </Paper>
      </Box>
    </Container>
  );
}; 